package com.dongdongshop.mq;

import com.dongdongshop.pojo.TbOrder;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;

//分布式事务
@RocketMQTransactionListener
public class RocketMQCallback implements RocketMQLocalTransactionListener {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    //回调方法
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        TbOrder order=(TbOrder) o;
//        System.out.println("订单id"+order.getOrderId());
//        System.out.println("商户订单号"+order.getPostFee());
//        System.out.println("交易流水号"+order.getShippingCode());
//        System.out.println("修改的状态"+order.getStatus());
        System.out.println("--------------------------------------------");
        System.out.println("拿到消息内容"+message.getPayload());
        System.out.println("拿到消息内容"+message.getHeaders());//两个消息的信息
        String messageId=message.getHeaders().getId().toString();
        try {
            System.out.println("调用mapper方法修改订单状态");
            redisTemplate.boundValueOps(messageId).set("1");
            return RocketMQLocalTransactionState.COMMIT;//返回一个成功确认
        }catch (Exception e) {
            redisTemplate.boundValueOps(messageId).set("2");
            return RocketMQLocalTransactionState.ROLLBACK;//返回一个失败
        }
    }

    //回查方法
    //如果上边方法没有向回调的方法（Tborderserviceimpl 里边的分布式事务）返回返回值的话，就走回查方法
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String messageId = message.getHeaders().getId().toString();
        String s= (String) redisTemplate.boundValueOps(messageId).get();
        if(s!=null &&s.equals("1")){
            return RocketMQLocalTransactionState.COMMIT;//返回一个成功确认
        }else if(s !=null &&s.equals("2")){
            return RocketMQLocalTransactionState.ROLLBACK;//返回一个失败
        }else{
            return RocketMQLocalTransactionState.UNKNOWN;//返回一个未知错误
        }
    }
}
